<template>
  <q-page class="cc-admin row">
    <div class="col bg-white shadow-2 q-ma-sm">
      <div class="row">
        <q-item class="col-md-3 col-sm-6 col-xs-12 items-center">
          <q-item-label>姓名：</q-item-label>
          <q-item-section>
            <q-input dense outlined v-model="searchForm.realname"></q-input>
          </q-item-section>
        </q-item>
        <q-item class="col-md-3 col-sm-6 col-xs-12 items-center">
          <q-item-label>电话：</q-item-label>
          <q-item-section>
            <q-input dense outlined v-model="searchForm.phone"></q-input>
          </q-item-section>
        </q-item>
        <q-item class="col-md-3 col-sm-6 col-xs-12 items-center">
          <q-item-section>
            <div class="row justify-center">
              <q-btn unelevated class="q-mr-sm no-border-radius" color="primary" icon="search" label="查询" :loading="loading" @click="query()" />
              <q-btn no-wrap outline unelevated class="q-mr-sm no-border-radius" color="secondary" icon="refresh" label="重置" @click="searchReset" />
            </div>
          </q-item-section>
        </q-item>
      </div>
      <q-table flat color="primary" class="cross_table" separator="cell" :columns="columns" :data="list" row-key="id" :pagination.sync="pagination" :visible-columns="group" @request="query" :rows-per-page-options="[10, 20, 50, 100]" :selection="mobile ? 'none' : 'multiple'" :selected.sync="selected">
        <template #top-right="table">
          <table-top-btns
            label="用户管理"
            modelName="user"
            :showAdd="true"
            :showDeleteBatch="false"
            :showFull="false"
            :showGroup="false"
            :table="table"
            :selected="selected"
            :importing="importing"
            :exporting="exporting"
            :importExcelUrlFull="importExcelUrlFull"
            :columns="columns"
            @groupChange="groupChange"
            @add="add"
            @importExcel="importExcel"
            @exportExcel="exportExcel"
            @showConfirm="showConfirm"
            :showImport="false"
            :showExport="false"
          />
        </template>
        <template #body-cell-companyId="props">
          <q-td key="companyId" :props="props">
            {{ getDictLabel(sysCompany, props.row.companyId) }}
          </q-td>
        </template>
        <template #body-cell-avatar="props">
          <q-td key="avatar" :props="props">
            <q-avatar v-if="props.row.avatar">
              <img style="width: 30px; height: 30px" :src="imagePath(props.row.avatar)" />
            </q-avatar>
          </q-td>
        </template>
        <template #body-cell-sex="props">
          <q-td key="sex" :props="props">{{ getDictLabel(sex, props.row.sex) }}</q-td>
        </template>
        <template #body-cell-status="props">
          <q-td key="status" :props="props">{{ getDictLabel(userStatus, props.row.status) }}</q-td>
        </template>
        <template #body-cell-delFlag="props">
          <q-td key="delFlag" :props="props">{{ getDictLabel(delFlag, props.row.delFlag) }}</q-td>
        </template>
        <template #body-cell-activitiSync="props">
          <q-td key="activitiSync" :props="props">{{ getDictLabel(activitiSync, props.row.activitiSync) }}</q-td>
        </template>
        <template #body-cell-officeId="props">
          <q-td key="sysDeptCode" :props="props">{{ getDictLabel(sysDepart, props.row.sysDeptCode) }}</q-td>
        </template>
        <template #body-cell-post="props">
          <q-td key="post" :props="props">{{ getDictLabel(sysPosition, props.row.post) }}</q-td>
        </template>
        <template #body-cell-isProxy="props">
          <q-td key="isProxy" :props="props">{{ getDictLabel(proxyOptions, props.row.isProxy) }}</q-td>
        </template>
        <template #body-cell-opt="props">
          <q-td :props="props" :auto-width="true">
            <cc-btn label="重置密码" color="primary" icon="mdi-key" @click="change(props.row)">
              <q-tooltip>重置密码</q-tooltip>
            </cc-btn>
            <cc-btn label="分配角色" color="primary" icon="engineering" @click="editUserRole(props.row)">
              <q-tooltip>分配角色</q-tooltip>
            </cc-btn>
            <cc-btn label="编辑" color="primary" icon="edit" @click="edit(props.row)">
              <q-tooltip>编辑</q-tooltip>
            </cc-btn>
            <btn-del label="用户表" @confirm="del(props.row)" />
          </q-td>
        </template>
      </q-table>
    </div>
    <cc-dialog ref="changePassWord" title="修改密码" @submit="changePassWord">
      <div class="col-12">
        <h5>用户账号：</h5>
        <q-input outlined readonly dense v-model="selectUser.username" />
      </div>
      <div class="col-12">
        <h5>用户姓名：</h5>
        <q-input outlined readonly dense v-model="selectUser.realname" />
      </div>

      <div class="col-6">
        <h5><q-icon name="star" color="red" />密码：</h5>
        <q-input outlined dense type="password" v-model="password" :rules="rules" />
      </div>
      <div class="col-6">
        <h5><q-icon name="star" color="red" />确认密码：</h5>
        <q-input outlined dense type="password" v-model="confirmpassword" :rules="rules" :error="!isValid">
          <template v-slot:error>两次输入密码不一致！</template>
        </q-input>
      </div>
    </cc-dialog>
    <cc-dialog ref="dialog" :title="`${editType}用户`" @submit="submitBefore">
      <div class="col-6">
        <h5><q-icon name="star" color="red" />登录账号：</h5>
        <q-input outlined dense square clearable v-model="form.username" type="text" :rules="[requiredTest]" @blur="checkUserName" />
      </div>
      <div class="col-6">
        <h5><q-icon name="star" color="red" />姓名：</h5>
        <q-input outlined dense square clearable v-model="form.realname" type="text" :rules="[requiredTest]" />
      </div>
      <div v-if="editType === '新建'" class="col-6">
        <h5><q-icon name="star" color="red" />密码：</h5>
        <q-input outlined dense v-model="form.password" type="password" :rules="[requiredTest]" />
      </div>
      <div class="col-6">
        <h5>头像：</h5>
        <div class="row wrap justify-center items-center content-center">
          <q-btn round @click="importAvatar">
            <q-avatar size="100px">
              <q-img style="width: 100px; height: 100px" :src="imageFullPath"></q-img>
            </q-avatar>
            <q-uploader auto-upload ref="avatarUploader" :max-files="1" class="hidden" fieldName="file" :headers="headers" accept="image/*" :url="uploadUrl" field-name="file" @uploaded="importedAvatar" />
            <q-tooltip>点击上传图片</q-tooltip>
          </q-btn>
        </div>
      </div>
      <div class="col-6">
        <h5>性别：</h5>
        <q-select outlined dense emit-value v-model="form.sex" map-options :options="sex" />
      </div>
      <div class="col-6">
        <h5>电子邮件：</h5>
        <q-input outlined dense square clearable v-model="form.email" type="text" />
      </div>

      <div class="col-6">
        <h5><q-icon name="star" color="red" />账号类型：</h5>
        <q-select outlined dense emit-value v-model="form.type" map-options :options="accounttype" :rules="[requiredTest]" @input="typeInput(form.type, form)" />
      </div>
      <div class="col-6">
        <h5><q-icon name="star" color="red" />身份证号：</h5>
        <q-input outlined dense v-model="form.idCard" :rules="[requiredTest, hcodeTest]" @blur="checkIdCard" />
      </div>
      <div class="col-6">
        <h5>电话：</h5>
        <q-input outlined dense square clearable v-model="form.phone" type="text" />
      </div>

      <div class="col-6">
        <h5>状态：</h5>
        <q-select outlined dense emit-value v-model="form.status" map-options :options="userStatus" />
      </div>
      <div class="col-6">
        <h5>工号：</h5>
        <q-input outlined dense square clearable v-model="form.workNo" type="text" />
      </div>
      <div class="col-6">
        <h5><q-icon name="star" color="red" />部门：</h5>
        <select-search outlined dense emit-value v-model="form.sysDeptCode" map-options :options="sysDept" :rules="[requiredTest]" @input="sysDeptCodeInput(form.sysDeptCode, form)" />
      </div>
      <div class="col-6">
        <h5>岗位：</h5>
        <select-search outlined dense emit-value v-model="form.post" map-options :options="sysPosition" @input="sysPostInput(form.post, form)" />
      </div>
      <div class="col-6">
        <h5>职责：</h5>
        <select-search multiple outlined dense emit-value v-model="dutyList" map-options :options="sysPostsDuty" />
      </div>
      <div class="col-6">
        <h5>代理人：</h5>
        <q-select outlined dense emit-value v-model="form.isProxy" map-options :options="proxyOptions" />
      </div>

      <!--<div class="col-6">
        <h5>所属子系统：</h5>
        <q-select  multiple outlined dense emit-value v-model="subSysCode" map-options :options="subSys" />
      </div>

       <div class="col-6" v-if="temporary">
        <h5><q-icon name="star" color="red" />期限天数：</h5>
        <q-input outlined dense square clearable v-model="form.durationDays" type="number"  @input="durationDaysInput(form.durationDays,form)" :rules="[requiredTest]"/>
      </div> -->
      <div class="col-6" v-if="temporary">
        <div class="dynamic-form-item">
          <h5><q-icon name="star" color="red" />开始日期</h5>
          <input-date-picker dense debounce="500" hide-bottom-space outlined v-model="form.startTime" type="date" :form="form" beginDate="" endDate="" lazy-rules :rules="[requiredTest]" />
        </div>
      </div>
      <div class="col-6" v-if="temporary">
        <div class="dynamic-form-item">
          <h5><q-icon name="star" color="red" />结束日期</h5>
          <input-date-picker dense debounce="500" hide-bottom-space outlined v-model="form.endTime" type="date" :form="form" beginDate="" endDate="" lazy-rules @input="endTimeInput(form.endTime, form)" :rules="[requiredTest]" />
        </div>
      </div>
    </cc-dialog>

    <listselect ref="listselectDialog" :unselectedList="unselectedRoleList" :selectList="selectedRoleList" :msg="selectTitle" @saveSelect="setRoles" />
    <confirm ref="confirmDialog" :msg="confirmMsg" @confirm="deleteBatch()" />
    <cc-loading :loading="loading" />
  </q-page>
</template>

<script>
import { IndexMixin } from 'boot/mixins';
import { getDictLabel } from 'boot/dictionary';
import confirm from 'components/confirm';
import listselect from 'components/listselect';
import { requiredTest, hcodeTest } from 'boot/inputTest';

export default {
  name: 'SysUser',
  mixins: [IndexMixin],
  components: {
    confirm,
    listselect,
    /* tree, */
  },
  data() {
    return {
      imageFullPath: '',
      showQuery: true,
      temporary: false,
      tableLabel: '展开',
      headers: [{ name: 'Authorization', value: localStorage.Authorization }],
      uploadUrl: `${process.env.BASE_URL}/sys/common/upload`,
      imgUrl: `${process.env.BASE_URL}/sys/common/static`,
      columns: [
        {
          name: 'index',
          align: 'center',
          label: '序号',
          field: 'index',
          headerClasses: 'cc-table-index',
        },
        {
          name: 'username',
          align: 'center',
          label: '账号',
          field: 'username',
        },
        {
          name: 'realname',
          align: 'center',
          label: '姓名',
          field: 'realname',
        },
        {
          name: 'userRoleNames',
          align: 'center',
          label: '用户角色',
          field: 'userRoleNames',
        },
        {
          name: 'avatar',
          align: 'center',
          label: '头像',
          field: 'avatar',
        },
        {
          name: 'post',
          align: 'center',
          label: '岗位',
          field: 'post',
        },
        {
          name: 'dutyNames',
          align: 'center',
          label: '职责',
          field: 'dutyNames',
        },
        {
          name: 'phone',
          align: 'center',
          label: '电话',
          field: 'phone',
        },
        {
          name: 'status',
          align: 'center',
          label: '状态',
          field: 'status',
        },
        {
          name: 'isProxy',
          align: 'center',
          label: '代理人',
          field: 'isProxy',
        },
        {
          name: 'opt',
          align: 'center',
          label: '操作',
          field: 'opt',
        },
      ],
      dutyList: [],
      sex: [
        { value: 1, label: '男' },
        { value: 2, label: '女' },
      ],
      userStatus: [
        { value: 1, label: '正常' },
        { value: 2, label: '冻结' },
      ],
      delFlag: [
        { value: '0', label: '正常' },
        { value: '1', label: '已删除' },
      ],
      proxyOptions: [
        { value: '0', label: '否' },
        { value: '1', label: '是' },
      ],
      activitiSync: [
        { value: '1', label: '同步' },
        { value: '0', label: '不同步' },
      ],
      sysPosition: [],
      sysCompany: [],
      selectUser: {},
      subSysCode: [],
      password: '',
      idCard: '',
      accounttype: [],
      confirmpassword: '',
      selectTitle: '',
      roleList: [],
      unselectedRoleList: [],
      selectedRoleList: [],
      sysDept: [],
      sysDeptName: null,
      sysOrg: [],
      subSys: [],

      sysPostsDuty: [],
      postName: null,
      companyName: null,
      url: {
        list: '/sys/user/list',
        add: '/sys/user/add',
        edit: '/sys/user/edit',
        delete: '/sys/user/delete',
        deleteBatch: '/sys/user/deleteBatch',
        exportXlsUrl: '/sys/user/exportXls',
        importExcelUrl: '/sys/user/importExcel',
        setUserRoles: '/sys/user/setUserRoles',
      },
      rules: [requiredTest],
    };
  },
  methods: {
    requiredTest,
    hcodeTest,
    getDictLabel,
    sysDeptCodeInput(v, row, editAfter) {
      // 这里给名称字段赋值
      if (v instanceof Array) {
        const nameArray = [];
        this.form.sysDeptName = '';
        v.forEach((id) => {
          const opt = this.sysDept.find((o) => o.value === id);
          if (opt) {
            nameArray.push(opt.label);
          }
          this.form.sysDeptName = nameArray.join(',');
        });
      } else {
        const opt = this.sysDept.find((o) => o.value === v);
        this.form.sysDeptName = opt ? opt.label : '';
      }
    },
    typeInput(v, row) {
      if (v === '4') {
        this.temporary = true;
      } else {
        this.temporary = false;
      }
    },

    sysPostInput(v, row, editAfter) {
      // 这里给名称字段赋值
      if (v instanceof Array) {
        const nameArray = [];
        this.form.postName = '';
        v.forEach((id) => {
          const opt = this.sysPosition.find((o) => o.value === id);
          if (opt) {
            nameArray.push(opt.label);
          }
          this.form.postName = nameArray.join(',');
        });
      } else {
        const opt = this.sysPosition.find((o) => o.value === v);
        this.form.postName = opt ? opt.label : '';
      }
    },

    companyIdInput(v, row, editAfter) {
      // 这里给名称字段赋值
      if (v instanceof Array) {
        const nameArray = [];
        this.form.companyName = '';
        v.forEach((id) => {
          const opt = this.sysCompany.find((o) => o.value === id);
          if (opt) {
            nameArray.push(opt.label);
          }
          this.form.companyName = nameArray.join(',');
        });
      } else {
        const opt = this.sysCompany.find((o) => o.value === v);
        this.form.companyName = opt ? opt.label : '';
      }
    },
    durationDaysInput(v, row) {
      const dateObj = new Date(row.startTime);
      dateObj.setDate(dateObj.getDate() + Number(v));
      const year = dateObj.getFullYear();
      const month = dateObj.getMonth() + 1;
      const day = dateObj.getDate();
      this.form.endTime = `${year}-${month}-${day}`;
    },
    endTimeInput(v, row) {
      const date1 = new Date(row.startTime);
      const date2 = new Date(v);
      // 计算时间差
      const diffTime = Math.abs(date2 - date1);
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
      // this.form.durationDays = '1';
      // console.log(this.form.durationDays);
    },
    addBefore() {
      this.dutyList = [];
      this.subSysCode = [];
      this.imageFullPath = '';
      if (this.form.sysDeptCode) {
        this.sysDeptCodeInput(this.form.sysDeptCode);
      }
      if (this.form.post) {
        this.sysPostInput(this.form.post);
      }
      if (this.form.companyId) {
        this.companyIdInput(this.form.companyId);
      }
      const now = new Date();
      const year = now.getFullYear();
      const month = now.getMonth() + 1;
      const day = now.getDate();
      this.form = {
        status: 1,
        isProxy: '0',
      };
      return true;
    },
    submitBefore() {
      if (this.dutyList) {
        this.form.dutyIds = this.dutyList.join(',');
      } else {
        this.form.dutyIds = '';
      }
      const nameArray = [];
      this.form.dutyNames = '';
      if (this.dutyList) {
        this.dutyList.forEach((id) => {
          const opt = this.sysPostsDuty.find((o) => o.value === id);
          if (opt) {
            nameArray.push(opt.label);
          }
          this.form.dutyNames = nameArray.join(',');
        });
      } else {
        this.form.dutyNames = '';
      }

      this.submit();
    },
    checkUserName() {
      if (this.form.username) {
        this.$axios.get(`/sys/user/checkUserName?username=${this.form.username}&id=${this.form.id}`).then((r) => {
          if (r.result) {
            this.form.username = '';
            this.$error('账号已经存在！');
          }
        });
      }
    },
    checkIdCard() {
      if (this.form.idCard) {
        this.$axios.get(`/sys/user/checkIdCard?idCard=${this.form.idCard}&id=${this.form.id}`).then((r) => {
          if (r.result) {
            this.form.idCard = '';
            this.$error('身份证号已经存在！');
          }
        });
      }
    },
    editAfter() {},
    editBefore(p) {
      if (p.dutyIds && p.dutyIds.length > 0) {
        this.dutyList = p.dutyIds.split(',');
      } else {
        this.dutyList = [];
      }
      this.imageFullPath = this.imagePath(p.avatar);
      if (p.type === '4') {
        this.temporary = true;
      } else {
        this.temporary = false;
      }
      return true;
    },
    selectCatalog(n) {
      this.sysDeptCode = n.id;
      this.query();
    },
    queryParam() {
      return {
        sysDeptCode: this.sysDeptCode,
      };
    },
    importAvatar() {
      this.$refs.avatarUploader.pickFiles();
    },
    importedAvatar({ xhr }) {
      const response = JSON.parse(xhr.responseText);
      if (response.success) {
        this.form.avatar = response.message;
        this.imageFullPath = this.imagePath(this.form.avatar);
        this.$q.notify('上传成功');
      } else {
        this.$q.notify({
          color: 'red',
          message: '上传失败',
        });
      }
      this.$refs.avatarUploader.removeUploadedFiles();
    },
    imagePath(src) {
      let path = '';
      if (src) {
        if (src.startsWith('http')) {
          return src;
        }
        path = `${this.imgUrl}/${src}`;
      }
      return path;
    },
    show() {
      this.showQuery = true;
      this.tableLabel = '收起';
    },
    hide() {
      this.showQuery = false;
      this.tableLabel = '展开';
    },
    initDict() {
      this.$axios.get('/sys/dictItem/selectItemsByDefId?defId=sysPosition').then((r) => {
        this.sysPosition = r;
      });
      this.$axios.get('/sys/dictItem/selectItemsByDefId?defId=sysRole').then((r) => {
        this.roleList = r;
      });
      this.$axios.get('/sys/dictItem/selectItemsByDictCode?dictCode=accountType').then((r) => {
        this.accounttype = r;
      });
      this.$axios.get('/sys/dictItem/selectItemsByDefId?defId=sysPosition').then((r) => {
        this.sysPostsDuty = r;
      });
      this.$axios.get('/sys/depart/getSysOrgCode?deptType=dept').then((r) => {
        this.sysDept = r;
      });
      this.$axios.get('/sys/org/getOrgCodeName').then((r) => {
        this.sysOrg = r;
      });
      this.$axios.get('/sys/dictItem/selectItemsByDefId?defId=subSys').then((r) => {
        this.subSys = r;
      });
      this.$axios.get('/sys/company/getCompanyName').then((r) => {
        this.sysCompany = r;
      });
    },
    change(row) {
      this.password = '';
      this.confirmpassword = '';
      this.selectUser = row;
      this.$axios.get(`/sys/company/getTenantInfo?username=${row.username}`).then(({ result }) => {
        this.$refs.changePassWord.show();
      });
    },
    changePassWord() {
      this.$axios
        .put('/sys/user/resetPassword', {
          confirmpassword: this.confirmpassword,
          password: this.password,
          username: this.selectUser.username,
        })
        .then((r) => {
          this.$info(r.message);
          this.$refs.changePassWord.hide();
        });
    },
    editUserRole(row) {
      this.selectUser = row;
      const { userRoleIdList } = row;
      this.unselectedRoleList = [];
      this.selectedRoleList = [];
      this.selectTitle = `用户[${row.realname}]分配角色`;
      this.roleList.forEach((role) => {
        if (userRoleIdList.includes(role.value)) {
          this.selectedRoleList.push(role);
        } else {
          this.unselectedRoleList.push(role);
        }
      });
      this.$refs.listselectDialog.show();
    },
    setRoles(roleList) {
      const selectedRoles = [];
      if (roleList && roleList.length > 0) {
        roleList.forEach((role) => {
          selectedRoles.push(role.value);
        });
      }
      this.$axios.put(`${this.url.setUserRoles}?userId=${this.selectUser.id}&selectedRoles=${selectedRoles.join(',')}`).then((r) => {
        if (r.success) {
          this.$refs.listselectDialog.hide();
          this.query();
        }
        this.$info(r.message);
      });
    },
  },
  mounted() {
    this.initDict();
  },
  computed: {
    isValid() {
      return this.confirmpassword === this.password;
    },
  },
};
</script>
<style lang="stylus"></style>
